﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace Foursquare
{
    public class FoursquareClient
    {
        private string clientId = "RGW2EGK1KQKFQGGPLY3LYPOO2ZBHGGDDSC41Z3YMFMHYM454";
        private string clientSecret = "3PUEIKTNGAZTJHERFDWC43J3TK0VUGZUWO1MPU1PBRR0XJDQ";

        public delegate void GetVenuesCompletedEventHandler(object sender, List<Venue> venues);
        public event GetVenuesCompletedEventHandler GetVenuesCompleted;

        public delegate void GetVenuesPhotosCompletedEventHandler(object sender, List<PhotoItem> venues);
        public event GetVenuesPhotosCompletedEventHandler GetVenuePhotosCompleted;

        #region GetVenuesNearby
        WebClient client = new WebClient();
        public void GetVenuesNearbyAsync(double lat, double lng)
        {
            if (GetVenuesCompleted == null)
            {
                throw new NullReferenceException("GetVenuesCompleted event handler is not set.");
            }
            if (client.IsBusy)
            {
                return;
            }

            string url = GetFoursquareApiUrl("venues/search",
                new KeyValuePair<string, string>("ll", string.Format("{0},{1}", lat, lng)),
                new KeyValuePair<string, string>("v", GetVersionString()));

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(url));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            DataContractJsonSerializer jsse = new DataContractJsonSerializer(typeof(FoursquareResponse));
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
            FoursquareResponse resp = jsse.ReadObject(ms) as FoursquareResponse;
            GetVenuesCompleted(this, resp.response.venues);
        }
        #endregion

        public void GetVenuePhotoAsync(string venueId, int limit, int offset)
        {
            if (GetVenuePhotosCompleted == null)
            {
                throw new NullReferenceException("GetVenuesCompleted event handler is not set.");
            }

            string url = GetFoursquareApiUrl("venues/" + venueId + "/photos",
                new KeyValuePair<string, string>("group", "venue"),
                new KeyValuePair<string, string>("limit", limit.ToString()),
                new KeyValuePair<string, string>("offset", offset.ToString()));

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadPhotoCompleted);
            client.DownloadStringAsync(new Uri(url));
        }

        void client_DownloadPhotoCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            DataContractJsonSerializer jsse = new DataContractJsonSerializer(typeof(FoursquareResponse));
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
            FoursquareResponse resp = jsse.ReadObject(ms) as FoursquareResponse;
            GetVenuePhotosCompleted(this, resp.response.photos.items);
        }

        #region Common Functions
        private string GetFoursquareApiUrl(string path, params KeyValuePair<string, string>[] parameters)
        {
            string paramString = "";
            foreach (KeyValuePair<string, string> param in parameters)
            {
                paramString += "&" + param.Key + "=" + param.Value;
            }
            string url = "https://api.foursquare.com/v2/{0}?client_id={1}&client_secret={2}{3}";
            return string.Format(url, path, clientId, clientSecret, paramString);
        }

        private string GetVersionString()
        {
            DateTime date = DateTime.Now;
            return date.ToString("yyyyMMdd");
        }
        #endregion
    }
}
